from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
#   /verifications/imagecodes/(?P<image_code_id>.+)/
from django_redis import get_redis_connection
from requests import Response
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from . import contants

class RegisserImageCodeAPIView(APIView):

    def __get__(self,request,image_code_id):

        text,image = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s'%image_code_id,contants.IMAGECODEEXPIRE,text)

        return HttpResponse(image,content_type='image/jpeg')

from .serializers import RegisterSmsCodeSerializer



class RegisterSmsCodeAPIView(APIView):

    def get(self,request,mobile):
        # 接收数据
        query_params = request.query_params
        # 校验数据
        # text = query_params.get('text')
        # image_code_id=query_params.get('image_code')


        serializer = RegisterSmsCodeSerializer(data=query_params)
        serializer.is_valid(raise_exception=True)

        # 生成一个短信验证码
        from  random import randint
        sms_code = '%06d'%randint(0,999999)
        CCP().send_template_sms(mobile,[sms_code,5],1)

        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_%s'%mobile,300,sms_code)
        # 返回相应
        return Response({'msg':'ok'})
